import serial
import time
import random

port = "/dev/ttyUSB0"  # Windows: "COMx"，Linux: "/dev/ttyUSBx"
baudrate = 115200


try:
    with serial.Serial(port, baudrate, timeout=1) as ser:
        print(f"Connected to port: {port}")
        while True:

            # mock data
            temp_001            = round(random.uniform(20.0, 160.0),1)
            vib_001             = round(random.uniform(0.0, 10.0), 1)
            cur_001             = random.randint(1, 60)
            press_01            = round(random.uniform(0.0, 10.0), 1)
            spd_001             = random.randint(30, 5000)
            status              = random.randint(0, 1)
            err_1               = random.randint(0, 1)
            err_2               = random.randint(0, 1)
            env_temp_room1      = round(random.uniform(20.0, 45.0),1)
            env_humidity_room1  = round(random.uniform(65.0, 99.0),1)
            alarm               = random.randint(0, 1)

            try:
                # Check if data is available
                if ser.in_waiting > 0:
                    data = ser.read(ser.in_waiting)  # Read incoming data
                    print(f"RS485 device received data: {data}")

                    # Add timestamp to the response
                    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    # echo_data = data + f" - resp @ {timestamp}".encode()

                    echo_data = data + f",{temp_001},{vib_001},{cur_001},{press_01},{spd_001},{status},{err_1},{err_2},{env_temp_room1},{env_humidity_room1},{alarm}".encode()
                    print(f"Echo data: {echo_data}")

                    ser.write(echo_data)  # Send response
                    ser.flush()
                    print(f"RS485 device echoed data: {echo_data} @ {timestamp}")
                    time.sleep(0.05)

            except Exception as e:
                print(f"Error during communication: {e}")
                break
except serial.SerialException as e:
    print(f"Failed to open serial port: {e}")
except KeyboardInterrupt:
    print("Exiting serial server.")



# import serial
# import time

# port = "/dev/ttyUSB0"  # Windows: "COMx"，Linux: "/dev/ttyUSBx"
# baudrate = 115200

# try:
#     with serial.Serial(port, baudrate, timeout=1) as ser:
#         print(f"Connected to port: {port}")
        
#         while True:
#             try:
#                 # **1. 读取 DTU 发送的轮询指令**
#                 if ser.in_waiting > 0:
#                     command = ser.read(ser.in_waiting)  # 读取 DTU 发送的指令
#                     print(f"Received polling command from DTU: {command}")

#                     # **2. 发送该指令给 RS485 设备**
#                     ser.write(command)
#                     ser.flush()
#                     print(f"Sent command to RS485: {command}")

#                     # **3. 等待 RS485 设备返回响应**
#                     time.sleep(0.1)  # 视设备响应速度调整
#                     response = ser.read(ser.in_waiting)  # 读取设备响应数据

#                     if response:
#                         print(f"Received response from RS485: {response}")

#                         # **4. 回传 RS485 设备的响应数据给 DTU**
#                         echo_data = response + b" - response data"
#                         ser.write(echo_data)  
#                         ser.flush()
#                         print(f"Echoed response to DTU: {echo_data}")
                
#                 time.sleep(0.01)  # 避免 CPU 100% 占用

#             except Exception as e:
#                 print(f"Error during communication: {e}")
#                 break
# except serial.SerialException as e:
#     print(f"Failed to open serial port: {e}")
# except KeyboardInterrupt:
#     print("Exiting serial server.")
